<?php

namespace app\admin\controller;

use think\Lang;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class MemberDa extends AdminControl {

    public function _initialize() {
        parent::_initialize();
        Lang::load(APP_PATH . 'admin/lang/'.config('default_lang').'/member.lang.php');
    }

    public function member() {
        $member_model = model('member');


        //会员级别
        $member_grade = $member_model->getMemberGradeArr();
        $search_field_value = input('search_field_value');
        $search_field_name = input('search_field_name');
        $condition = array();
        $memberda_type_name_search = input('memberda_type_name');
        if ($memberda_type_name_search) {
            $condition['memberda_type_name'] = $memberda_type_name_search;
        }

        $enterprise_name_search = input('enterprise_name');
        if ($enterprise_name_search) {
            $condition['enterprise_name'] = $enterprise_name_search;
        }

        $enterprise_type_name_search = input('enterprise_type_name');
        if ($enterprise_type_name_search) {
            $condition['enterprise_type_name'] = $enterprise_type_name_search;
        }

        $memberda_type_name_search = input('memberda_type_name');
        if ($memberda_type_name_search) {
            $condition['memberda_type_name'] = $memberda_type_name_search;
        }
        if ($search_field_value != '') {
            switch ($search_field_name) {
                case 'member_name':
                    $condition['member_name'] = array('like', '%' . trim($search_field_value) . '%');
                    break;
                case 'member_email':
                    $condition['member_email'] = array('like', '%' . trim($search_field_value) . '%');
                    break;
                case 'member_mobile':
                    $condition['member_mobile'] = array('like', '%' . trim($search_field_value) . '%');
                    break;
                case 'member_truename':
                    $condition['member_truename'] = array('like', '%' . trim($search_field_value) . '%');
                    break;
            }
        }
        $search_state = input('search_state');
        switch ($search_state) {
            case 'no_informallow':
                $condition['inform_allow'] = '2';
                break;
            case 'no_isbuy':
                $condition['is_buylimit'] = '0';
                break;
            case 'no_isallowtalk':
                $condition['is_allowtalk'] = '0';
                break;
            case 'no_memberstate':
                $condition['member_state'] = '0';
                break;
        }
        //会员等级
        $search_grade = intval(input('get.search_grade'));
        if ($search_grade>0 && $member_grade) {
            if (isset($member_grade[$search_grade + 1]['exppoints'])) {
                $condition['member_exppoints'] = array('between',array($member_grade[$search_grade]['exppoints'],$member_grade[$search_grade + 1]['exppoints']));
            }else{
                $condition['member_exppoints'] = array('egt', $member_grade[$search_grade]['exppoints']);
            }
        }
        //时间
        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $condition['member_addtime'] = array('between', array($start_unixtime, $end_unixtime));
        }

        //排序
        $order = trim(input('get.search_sort'));
        if (!in_array($order,array('member_logintime desc','member_loginnum desc'))) {
            $order = 'member_id desc';
        }

        $member_list = $member_model->getMemberDaList($condition, '*', 10, $order);

        // 查询所有大客户类型
//        $member_da_type_array = [];
//        $member_da_type = \app\common\model\MemberDaType::select();
//        if ($member_da_type) {
//            foreach ($member_da_type as $key => $val) {
//                $member_da_type_arr[] = $val->toArray();
//            }
//            foreach ($member_da_type_arr as $key => $val) {
//                $member_da_type_array[$val['id']] = $val['title'];
//            }
//        }

        //整理会员信息
        if (is_array($member_list) && !empty($member_list)) {
            foreach ($member_list as $k => $v) {
//                if ($member_da_type_array) {
//                    if (isset($member_da_type_array[$v['enterprise_type']])) {
//                        $member_list[$k]['enterprise_type_title'] = $member_da_type_array[$v['enterprise_type']];
//                    } else {
//                        $member_list[$k]['enterprise_type_title'] = '';
//                    }
//                } else {
//                    $member_list[$k]['enterprise_type_title'] = '';
//                }
                $member_list[$k]['member_addtime'] = $v['member_addtime'] ? date('Y-m-d H:i:s', $v['member_addtime']) : '';
                $member_list[$k]['member_logintime'] = $v['member_logintime'] ? date('Y-m-d H:i:s', $v['member_logintime']) : '';
                $member_list[$k]['member_grade'] = ($t = $member_model->getOneMemberGrade($v['member_exppoints'], false, $member_grade)) ? $t['level_name'] : '';
            }
        }
        $this->assign('member_grade', $member_grade);
        $this->assign('search_sort', $order);
        $this->assign('search_field_name', trim($search_field_name));
        $this->assign('search_field_value', trim($search_field_value));
        $this->assign('member_list', $member_list);
        $this->assign('show_page', $member_model->page_info->render());

        $this->assign('filtered', $condition ? 1 : 0); //是否有查询条件

        $this->setAdminCurItem('member');
        return $this->fetch();
    }

    public function add() {
        if (!request()->isPost()) {
          $enterprisetype_info = db('enterprisetype')->where('status','1')->select();
           $this->assign('enterprisetype_info', $enterprisetype_info);

            $memberda_type_info = db('member_da_type')->where('status','1')->select();
            $this->assign('memberda_type_info', $memberda_type_info);
           $this->setAdminCurItem('add');
            return $this->fetch();
        } else {
            $data = input('post.');
            $member_info = db('member')->where('member_name',$data['member_name'])->find();
            if(!empty($member_info)){
                return json(['code' => -1, 'msg' => '该账号已存在']);
            }
            $enterprise_type_info = db('enterprisetype')->where('id',$data['enterprise_type_id'])->find();
            $memberda_type_info = db('member_da_type')->where('id',$data['member_da_type_id'])->find();
            $store_info = db('store')->where('store_id',config('store_id'))->find();

            #shen 1/9 需要添加两个表 member  和store表
            $insert_member = array(
                'member_name' => input('post.member_name'),
                'member_password' => input('post.member_password'),
                'member_nickname' => input('post.member_nickname'),
                'member_avatar' => input('post.portrait'),
                'member_qq' => input('post.member_qq'),
                'enterprise_name' => input('post.enterprise_name'),
                'member_addtime' => TIMESTAMP,
                'member_loginnum' => 0,
                'enterprise_type' => input('post.enterprise_type_id'),
                'enterprise_type_name'=> $enterprise_type_info['name'],
                'enterprise_license' => input('post.license'),
                'contact_title' => input('post.contact_title'),
                'contact_name' => input('post.contact_name'),
                'contact_phone' => input('post.contact_phone'),
                'contact_landline' => input('post.contact_landline'),
                'contact_address' => input('post.contact_address'),
                'inviter_id'=>0,
                'invite_parent_code'=>'pt',
                'invite_store_id'=>config('store_id'),
                'invite_store_name'=>$store_info['store_name'],
                'invite_name'=>'平台',
                'member_type'=>'8',
                'invite_type'=>'9',
                'memberda_type_id'=>input('post.member_da_type_id'),
                'memberda_type_name'=>$memberda_type_info['title']


            );
           // p($insert_member);die;
            $member_model = model('Member');
            $result = $member_model->addMember($insert_member);
            if ($result) {
             $insert_store = array(
                 'store_name' => input('post.member_nickname'),
                 'member_id' => $result,
                 'member_name' => input('post.member_name'),
                 'seller_name' => input('post.member_name'),
                 'store_addtime' => TIMESTAMP,
                 'store_state' => '1',
                 'store_avatar' => input('post.portrait'),
                 'store_qq'=> input('post.member_qq'),
                 'store_phone' => input('post.member_name'),
                 'store_seller_type' => 3,
             );

                $store_id = db('store')->insertGetId($insert_store);

                  $insert_seller = array(

                 'seller_name' => input('post.member_name'),
                 'member_id' => $result,
                 'sellergroup_id' => 0,
                 'store_id' => $store_id,
                 'is_admin' => 1,
                 'position' => '1',

                  );

                   $seller_id = db('seller')->insertGetId($insert_seller);


                if($seller_id){
                    return json(['code' => 1, 'url' => url('Member_da/member'), 'msg' => '添加成功']);
                }else{
                    return json(['code' => 0, 'url' => url('Member_da/member'), 'msg' => '添加失败']);
                }
            } else {
                return json(['code' => 0, 'url' => url('Member_da/member'), 'msg' => '添加失败']);
            }
        }
    }

    public function edit() {
        $member_id = input('param.member_id');
        if (empty($member_id)) {
            $this->error(lang('param_error'));
        }
        $member_model = model('member');
        if (!request()->isPost()) {
            $condition['member_id'] = $member_id;

            $member_array = $member_model->getMemberInfo($condition);
            $this->assign('member_array', $member_array);

           $enterprisetype_info = db('enterprisetype')->where('status','1')->select();
           $this->assign('enterprisetype_info', $enterprisetype_info);

           $file_http = db('config')->where('code', 'qiniu_http')->find();
           $this->assign('http_name', $file_http['value']);
            $memberda_type_info = db('member_da_type')->where('status','1')->select();
            $this->assign('memberda_type_info', $memberda_type_info);
           $this->setAdminCurItem('edit');
            return $this->fetch();
        } else {
            $member_info = db('member')->where(array('member_id'=>intval($member_id)))->find();
            if (input('post.member_password')) {
                if($member_info['member_password'] == md5(input('post.member_password'))){
                    return json(['code' => -1, 'url' => '', 'msg' => ' 密码不能和之前相同']);
                }
            }
            //p(input('post.'));die;
            $enterprise_type_info = db('enterprisetype')->where('id',input('post.enterprise_type_id'))->find();
            $memberda_type_info = db('member_da_type')->where('id',input('post.member_da_type_id'))->find();
            #shen 1/10 需要编辑两个表 member  和store表
                $update_member = array(
                'member_nickname' => input('post.member_nickname'),
                'member_avatar' => input('post.portrait'),
                'member_qq' => input('post.member_qq'),
                'enterprise_name' => input('post.enterprise_name'),
                // 'member_addtime' => TIMESTAMP,
                'member_loginnum' => 0,
                'enterprise_type' => input('post.enterprise_type_id'),
                'enterprise_type_name'=> $enterprise_type_info['name'],
                'enterprise_license' => input('post.license'),
                'contact_title' => input('post.contact_title'),
                'contact_name' => input('post.contact_name'),
                'contact_phone' => input('post.contact_phone'),
                'contact_landline' => input('post.contact_landline'),
                'contact_address' => input('post.contact_address'),
                'memberda_type_id'=>input('post.member_da_type_id'),
                'memberda_type_name'=>$memberda_type_info['title']
            );

            if (input('post.member_password')) {
                $update_member['member_password'] = md5(input('post.member_password'));
            }


            $result = $member_model->editMember(array('member_id'=>intval($member_id)),$update_member);
            if ($result) {
                $update_store = array(
                 'store_name' => input('post.member_nickname'),
                 'store_avatar' => input('post.portrait'),
                 'store_qq'=> input('post.member_qq'),
                 'store_phone' => input('post.member_name')
             );

             db('store')->data($update_store)->where('member_id',$member_id)->update();
            return json(['code' => 1, 'url' => url('Member_da/member'), 'msg' => '编辑成功']);
            } else {
            return json(['code' => 0, 'url' => url('Member_da/member'), 'msg' => ' 编辑失败']);
            }
        }
    }

     /*
     设置授信
     */
    public function set_credit() {

        $member_id = input('param.member_id');
        if (empty($member_id)) {
            $this->error(lang('param_error'));
        }
        $member_model = model('member');
        if (!request()->isPost()) {
            $condition['member_id'] = $member_id;
            $member_array = $member_model->getMemberInfo($condition);
            $this->assign('member_info', $member_array);
            $this->setAdminCurItem('index');
            return $this->fetch();
        } else {
            $data = input('post.');
            $update_member['credit_num'] = $data['credit_num'];
            $update_member['credit_status'] = 1;
            $update_member['credit_day'] = intval($data['credit_day']);
            $update_member['credit_create_time'] = time();
            $update_member['credit_end_time'] = time()+intval($data['credit_day'])*24*60*60;

            $store_info = db('store')->where('member_id',$member_id)->find();
            db('store')->where('store_id',$store_info['store_id'])->data($update_member)->update();
            $res = db('member')->data($update_member)->where('member_id',$data['member_id'])->update();
            if($res){
                 dsLayerOpenSuccess('操作成功');
            } else {
                 dsLayerOpenSuccess('操作失败');
            }
        }
    }

    /*
     设置工时
     */
    public function set_working() {

        $member_id = input('param.member_id');
        if (empty($member_id)) {
            $this->error(lang('param_error'));
        }
        $member_model = model('member');
        if (!request()->isPost()) {
            $condition['member_id'] = $member_id;
            $member_array = $member_model->getMemberInfo($condition);
            $this->assign('member_info', $member_array);
            $this->setAdminCurItem('index');
            return $this->fetch();
        } else {
            $data = input('post.');
            $update_member['working_status'] = 1;
            $update_member['maintain_money'] = $data['maintain_money'];
            $update_member['install_money'] = $data['install_money'];
            $update_member['dismantle_money'] = $data['dismantle_money'];
            $update_member['repair_money'] = $data['repair_money'];
              $res = db('member')->data($update_member)->where('member_id',$data['member_id'])->update();
            if($res){
                 dsLayerOpenSuccess('操作成功');
            } else {
                 dsLayerOpenSuccess('操作失败');
            }
        }
    }


    public function show() {

        $member_id = input('param.member_id');
        if (empty($member_id)) {
            $this->error(lang('param_error'));
        }
        $member_model = model('member');
            $condition['member_id'] = $member_id;
            $member_array = $member_model->getMemberInfo($condition);
            $this->assign('member_array', $member_array);
             $file_http = db('config')->where('code', 'qiniu_http')->find();
           $this->assign('http_name', $file_http['value']);
            return $this->fetch();


    }

    /**
     * 清除授信
     */
    public function cancel_credit()
    {
       $member_id = intval(input('member_id'));
       if($member_id<=0){
        $this->error('操作失败');
       }

        $member_info = db('member')->where('member_id',$member_id)->find();
            if(empty($member_id)){
                $this->error('操作失败');
               }

         $data['credit_num']  ='';
         $data['credit_status']  = '';
         $data['credit_create_time'] = '';
         $data['credit_end_time'] = '';
         $data['credit_day'] = 0;
        $store_info = db('store')->where('member_id',$member_id)->find();
        db('store')->where('store_id',$store_info['store_id'])->data($data)->update();
         $res = db('member')->where('member_id',$member_id)->data($data)->update();
          if ($res) {
            ds_json_encode(10000, '操作成功');
            } else {
            ds_json_encode(10000, '操作失败');
            }


        }

         /**
     * 清除工时
     */
    public function cancel_working()
    {
       $member_id = intval(input('member_id'));
       if($member_id<=0){
        $this->error('操作失败');
       }

        $member_info = db('member')->where('member_id',$member_id)->find();
            if(empty($member_id)){
                $this->error('操作失败');
               }

            $data['working_status'] = 0;
            $data['maintain_money'] = '';
            $data['install_money'] = '';
            $data['dismantle_money'] = '';
            $data['repair_money'] = '';

         $res = db('member')->where('member_id',$member_id)->data($data)->update();
          if ($res) {
            ds_json_encode(10000, '操作成功');
            } else {
            ds_json_encode(10000, '操作失败');
            }


        }

    /*
     ajax 上传图片

    */
    public function ajax_upload()
    {
        $file_type = array('0' => 'image/jpeg', '1' => 'image/jpg', '2' => 'image/png');
        if (in_array($_FILES['file']['type'], $file_type)) {
            $file_name = input('post.name');
            $upload_info = upload_qiniu('file');
            return $upload_info;
        } else {
            return $data['msg'] = 0;

        }
    }

    /**
     * ajax操作
     */
    public function ajax() {
        $branch = input('param.branch');

        switch ($branch) {
            /**
             * 验证会员是否重复
             */
            case 'check_user_name':
                $member_model = model('member');
                $condition['member_name'] = input('param.member_name');
                $condition['member_id'] = array('neq', intval(input('get.member_id')));
                $list = $member_model->getMemberInfo($condition);
                if (empty($list)) {
                    echo 'true';
                    exit;
                } else {
                    echo 'false';
                    exit;
                }
                break;
            /**
             * 验证邮件是否重复
             */
            case 'check_email':
                $member_model = model('member');
                $condition['member_email'] = input('param.member_email');
                $condition['member_id'] = array('neq', intval(input('param.member_id')));
                $list = $member_model->getMemberInfo($condition);
                if (empty($list)) {
                    echo 'true';
                    exit;
                } else {
                    echo 'false';
                    exit;
                }
                break;
        }
    }

    /**
     * 设置会员状态
     */
    public function memberstate() {
        $member_id = input('param.member_id');
        $member_id_array = ds_delete_param($member_id);
        if ($member_id_array == FALSE) {
            ds_json_encode('10001', lang('param_error'));
        }
        $data['member_state'] = input('param.member_state') ? input('param.member_state') : 0;

        $condition = array();
        $condition['member_id'] = array('in', $member_id_array);
        $result = db('member')->where($condition)->update($data);
        if ($result>=0) {
            foreach ($member_id_array as $key => $member_id) {
                dcache($member_id, 'member');
            }
            $this->log(lang('ds_edit') .  '[ID:' . implode(',', $member_id_array) . ']', 1);
            ds_json_encode('10000', lang('ds_common_op_succ'));
        }else{
            ds_json_encode('10001', lang('ds_common_op_fail'));
        }
    }

    /**
     * 获取卖家栏目列表,针对控制器下的栏目
     */
    protected function getAdminItemList() {
        $menu_array = array(
            array(
                'name' => 'member',
                'text' => lang('ds_manage'),
                'url' => url('Member_da/member')
            ),
        );
        if (request()->action() == 'add' || request()->action() == 'member') {
            $menu_array[] = array(
                'name' => 'add',
                'text' => lang('ds_add'),
               // 'url' => "javascript:dsLayerOpen('".url('Member_da/add')."','".lang('ds_add')."')"
                'url' => url('Member_da/add')
            );
        }
        if (request()->action() == 'edit') {
            $menu_array[] = array(
                'name' => 'edit',
                'text' => '编辑',
               // 'url' => "javascript:dsLayerOpen('".url('Member_da/add')."','".lang('ds_add')."')"
                'url' => url('Member_da/edit',['member_id'=>$_GET['member_id']])
            );
        }
        return $menu_array;
    }

}

?>
